<script setup lang="ts">
import { ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { compile } from 'path-to-regexp'

const route = useRoute()
const router = useRouter()

const levelList = ref<RouteRecordRaw[]>([])

watch(() => route.path, (nVal: string) => {
  if (nVal.startsWith('/redirect/'))
    return
  getBreadcrumb()
}, { immediate: true })

function getBreadcrumb() {
  const matched = route.matched.filter(item => item.meta?.title)
  const [firstRoute, ...otherRoutes] = matched
  const hasRedirectPage = otherRoutes.some((item: any) => item.path === firstRoute?.redirect)
  const matchedAll = hasRedirectPage ? otherRoutes : matched

  levelList.value = matchedAll.filter((item: any) => item.meta?.title && item.meta?.breadcrumb !== false)
}

// 解决动态id作为路径问题
function pathCompile(path: string) {
  const { params } = route
  const toPath = compile(path)
  return toPath(params)
}

function handleLink(item: any) {
  const { redirect, path } = item
  const { pageNo, pageSize } = route.query
  if (redirect) {
    router.push({ path: redirect, query: { pageNo, pageSize } })
    return
  }
  router.push({ path: pathCompile(path), query: { pageNo, pageSize } })
}
</script>

<template>
  <a-breadcrumb class="app-breadcrumb" separator="/">
    <a-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
      <span v-if="item?.redirect! === 'noRedirect' || index === levelList.length - 1" class="no-redirect">{{
        item.meta?.title }}</span>
      <a v-else @click.prevent="handleLink(item)">{{ item.meta?.title! }}</a>
    </a-breadcrumb-item>
  </a-breadcrumb>
</template>

<style lang="less" scoped>
.app-breadcrumb.ant-breadcrumb {
  display: inline-block;
  font-size: @font-size-large;
  margin-left: 8px;
  font-family: 'Web_SemiBold';

  a {
    height: auto;
  }

  .no-redirect {
    cursor: text;
  }
}
</style>
